package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.dao.EmployeeDao;
import com.itheima.entity.Employee;
import com.itheima.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


/**
 * 员工业务层实现类
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeDao employeeDao;

    @Override
    public Employee login(Employee employee) {

        if ( employee == null){
            System.out.println("对象为null");

        }
        else{
            if (employee.getUsername()==null || employee.getPassword() == null){

                System.out.println("账号或者密码有问题");
            }
            else{
                LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper();
                lqw.eq(Employee::getUsername, employee.getUsername())
                   .eq(Employee::getPassword,
                DigestUtils.md5DigestAsHex(employee.getPassword().getBytes()));
              return   employeeDao.selectOne(lqw);
            }
        }

        return null;
    }

    @Override
    public Integer addEmployee(Employee employee) {
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername, employee.getUsername());
        System.out.println("---"+employee.getUsername());
        Employee resultEmployee = employeeDao.selectOne(lqw);
        // username 唯一
        if (resultEmployee == null){
            return  employeeDao.insert(employee);
        }
        else{
            return null;
        }


    }

    @Override
    public IPage<Employee> getEmployee(Integer page, Integer pageSize,String name) {
        IPage<Employee> employeeIPage = new Page<>();
        employeeIPage.setPages(page);
        employeeIPage.setSize(pageSize);
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper();
//        lqw.like(Employee::getName,name);
//        lqw.like(StringUtils.isEmpty(name),Employee::getName,name);
        lqw.like(name!=null,Employee::getName,name);
        lqw.orderByDesc(Employee::getUpdateTime);//更新时间排序

        return  employeeDao.selectPage(employeeIPage,lqw);
    }

    @Override
    public Integer updateEmployeeStatus(Employee employee) {

        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getId,employee.getId());


        return  employeeDao.update(employee,lqw);
    }

    @Override
    public Employee getByIdEmployee(Integer id) {

        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getId,id);

        return   employeeDao.selectById(id);
    }

}
